package com.heima.admin.service.Impl;

import com.alibaba.fastjson.JSON;

import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.aliyun.GreeTextScan;
import com.heima.aliyun.GreenImageScan;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service
@Slf4j
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {


    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    ArticleFeign articleFeign;
    @Autowired
    AdSensitiveMapper adSensitiveMapper;

    @Autowired
    GreeTextScan greeTextScan;
    @Autowired
    GreenImageScan greenImageScan;

    @Autowired
    AdChannelMapper adChannelMapper;


    /**
     * 自媒体文章审核
     *
     * @param wmNewsId
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void autoScanByMediaNewsId(Integer wmNewsId) {
        //参数校验
        if (wmNewsId == null) {
            log.error("当前的id为空");
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
            return;
        }
        //1.根据文章的id查询自媒体文章

        WmNews wmNews = wemediaFeign.findById(wmNewsId);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.WMNEWS_IS_EMPTY);
            return;
        }
        //2.文章状态=4(人工审核通过) 且发布时间小于等于当前时间,直接保存到文章库
        if (wmNews.getStatus().equals(WmNews.Status.ADMIN_SUCCESS.getCode())
                && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            saveAppArticle(wmNews);
            return;
        }
        //3.文章状态=8(文章审核通过,未发布) 且发布时间小于等于当前时间,直接保存到文章库

        if (wmNews.getStatus().equals(WmNews.Status.SUCCESS.getCode())
                && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            saveAppArticle(wmNews);
            return;
        }
        //4.文章状态=1 未审核
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {

            Map<String, Object> contentAndImagesResult = getTextAndImages(wmNews);
            //4.1 自管理敏感词
            String content = contentAndImagesResult.get("content").toString();
            boolean isSensitiveScan = handleSensitive(content, wmNews);
            //如果isSensitiveScan为false,则包含敏感词,加上!就是true,直接跳出不往下执行
            if (!isSensitiveScan) return;
            //4.2 阿里云-文本内容审核
//            boolean isTextScan = handleText(content, wmNews);
//            if (!isTextScan) return;
//            //4.3 阿里云-图片审核
//            Object image = contentAndImagesResult.get("image");
//            boolean isImageScan = handleImage((List) image, wmNews);
//            if (!isImageScan) return;
            //4.4 如果发布时间 大于 当前时间,修改wmNews 文章状态=8
            if (wmNews.getPublishTime().getTime()>System.currentTimeMillis()){
                updateWmNews(wmNews,WmNews.Status.SUCCESS.getCode(),"文章审核通过,待发布");
                return;
            }

            //5 审核通过,保存文章相关信息(三张表),修改文章的状态=9 已发布
            saveAppArticle(wmNews);

        }

    }

    private boolean handleImage(List<String> image, WmNews wmNews) {
        boolean flag = true;
        if (image == null || image.size() == 0) {
            return flag;
        }
        try{
        image = image.stream().distinct().collect(Collectors.toList());
        Map map = greenImageScan.imageUrlScan(image);

        if (map.get("suggestion").equals("block")){
            updateWmNews(wmNews, (short) 2,"图片违规");
            flag=false;
        }
        if (map.get("suggestion").equals("review")){
            updateWmNews(wmNews, (short) 3,"转人工审核");
            flag=false;
        }
        }catch (Exception e){
            updateWmNews(wmNews, (short) 3,"阿里云审核失败");
            flag=false;
        }

        return flag;
    }



    private boolean handleText(String content, WmNews wmNews) {

        boolean flag = true;

        try {
            Map map = greeTextScan.greeTextScan(content);
            if (map.get("suggestion").equals("block")) {
                flag = false;
                updateWmNews(wmNews, (short) 2, "文章中有敏感词汇");
            }
            if (map.get("suggestion").equals("review")) {
                flag = false;
                updateWmNews(wmNews, (short) 3, "文章中内容需要人工审核");
            }

        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(wmNews, (short) 3, "阿里云内容审核失败");
        }

        return flag;
    }

    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        List<String> allSensitive = adSensitiveMapper.findAllSensitive();
        SensitiveWordUtil.initMap(allSensitive);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0) {
            updateWmNews(wmNews, (short) 2, "文章中包含敏感词" + map);
            flag = false;
        }
        return flag;
    }

    private void updateWmNews(WmNews wmNews, Short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        ResponseResult responseResult = wemediaFeign.updateWmNews(wmNews);
        if (!responseResult.getCode().equals(0)) {
            CustException.cust(AppHttpCodeEnum.WMNEWS_UPDATE_ERROR);
        }
    }


    private Map<String, Object> getTextAndImages(WmNews wmNews) {
        //1 获取文章内容并转换对象
        String contents = wmNews.getContent();
        if (StringUtils.isBlank(contents) || contents.length() > 10000) {
            return null;
        }
        List<Map> jsonArray = JSON.parseArray(contents, Map.class);
        //2 解析内容文本 Stream 流优化 --> String
        String collectList = jsonArray.stream()
                .filter(x -> x.get("type").equals("text"))
                .map(y -> y.get("value").toString())
//                .collect(Collectors.joining());
                .collect(Collectors.joining("_iamnull_"));
        // 文章标题 参与审核
        collectList = wmNews.getTitle() + "_iamnull_" + collectList;
        //3 解析内容图片
        List<String> images = jsonArray.stream().filter(x -> x.get("type").equals("image"))
                .map(y -> y.get("value").toString())
                .collect(Collectors.toList());
        //4 处理封面前缀 1.jpg 2.jpg
        String imagesCover = wmNews.getImages();
        if (StringUtils.isNotBlank(imagesCover)) {
            // 添加到内容图片列表

            images.addAll(Stream.of(imagesCover.split(","))
                    .map(x -> webSite + x)
                    .collect(Collectors.toList()));
        }

        //5 封装结果

        Map<String, Object> result = new HashMap<>();
        result.put("content", collectList);
        result.put("image", images);
        return result;
    }


    private void saveAppArticle(WmNews wmNews) {
        //保存app相关文章
        ResponseResult responseResult = saveArticle(wmNews);
        if (!responseResult.getCode().equals(0)){
            throw new RuntimeException("文章保存失败");
        }
        //修改自媒体文章状态,状态为9 审核通过
        // data 设置文章ID
        wmNews.setArticleId((Long) responseResult.getData());
        // 更新自媒体文章状态
        updateWmNews(wmNews, WmNews.Status.PUBLISHED.getCode(), "已发布");

    }

    private ResponseResult saveArticle(WmNews wmNews) {
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,articleDto);
        articleDto.setId(null);
        if(wmNews.getArticleId()!=null){
            articleDto.setId(wmNews.getArticleId());
        }
        articleDto.setLayout(wmNews.getType());
        articleDto.setFlag((byte) 0);

        //设置频道
        if(wmNews.getChannelId()!=null){
            articleDto.setChannelId(wmNews.getChannelId());
            AdChannel adChannel = adChannelMapper.selectById(wmNews.getChannelId());
            if (adChannel!=null){
                articleDto.setChannelName(adChannel.getName());
            }
        }

        //设置作者信息
        WmUser wmUser = wemediaFeign.findWmUserById(wmNews.getUserId());
        if(wmUser==null||wmUser.getStatus().intValue()!=9){
            CustException.cust(AppHttpCodeEnum.APUSER_LOCKED);
        }
        if(StringUtils.isNotBlank(wmUser.getName())){
            articleDto.setAuthorName(wmUser.getName());
        }

        //存储文章内容
        articleDto.setContent(wmNews.getContent());

        return articleFeign.saveArticle(articleDto);


    }
}